package com.lzb.browser.utils;

import android.os.Handler;
import android.os.Looper;

import org.json.JSONException;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpUtils {
    
    private static OkHttpUtils instance;
    private OkHttpClient client;
    private Handler handler;
    
    // 单例模式
    public static OkHttpUtils getInstance() {
        if (instance == null) {
            synchronized (OkHttpUtils.class) {
                if (instance == null) {
                    instance = new OkHttpUtils();
                }
            }
        }
        return instance;
    }
    
    private OkHttpUtils() {
        // 初始化 OkHttpClient
        client = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)  // 连接超时
                .readTimeout(15, TimeUnit.SECONDS)     // 读取超时
                .writeTimeout(15, TimeUnit.SECONDS)  // 写入超时
                .build();
        
        handler = new Handler(Looper.getMainLooper());
    }
    
    /**
     * GET 请求（异步）
     * @param url 请求地址
     * @param callback 回调接口
     */
    public void get(String url, HttpCallback callback) {
        Request request = new Request.Builder()
                .url(url)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                .build();
        
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.post(() -> callback.onFailure(e.getMessage()));
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    handler.post(() -> callback.onSuccess(result));
                } else {
                    handler.post(() -> callback.onFailure("Request failed: " + response.code()));
                }
            }
        });
    }
    
    /**
     * GET 请求带参数
     * @param url 基础地址
     * @param params 参数Map
     * @param callback 回调接口
     */
    public void getWithParams(String url, Map<String, String> params, HttpCallback callback) {
        StringBuilder urlBuilder = new StringBuilder(url);
        
        if (params != null && !params.isEmpty()) {
            urlBuilder.append("?");
            int i = 0;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (i > 0) {
                    urlBuilder.append("&");
                }
                urlBuilder.append(entry.getKey())
                         .append("=")
                         .append(entry.getValue());
                i++;
            }
        }
        
        get(urlBuilder.toString(), callback);
    }
    
    /**
     * 取消所有请求
     */
    public void cancelAllRequests() {
        for (Call call : client.dispatcher().queuedCalls()) {
            call.cancel();
        }
        for (Call call : client.dispatcher().runningCalls()) {
            call.cancel();
        }
    }
    
    /**
     * HTTP 回调接口
     */
    public interface HttpCallback {
        void onSuccess(String result);
        void onFailure(String error);
    }
}